import 'dart:io';

import 'package:flutter_app/bean/app_set_info_entity.dart';
import 'package:flutter_app/bean/update_app_entity.dart';
import 'package:flutter_app/manager/AppSetInfoManager.dart';
import 'package:flutter_app/manager/UserInfoManager.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/network/UrlPath.dart';
import 'package:flutter_app/ui/login/login_view.dart';
import 'package:flutter_app/ui/main/main_view.dart';
import 'package:flutter_app/utils/DialogUtils.dart';
import 'package:flutter_app/utils/PackageInfoUtils.dart';
import 'package:flutter_app/utils/amap_utils.dart';
import 'package:flutter_app/utils/channel/CommonChannel.dart';
import 'package:flutter_app/utils/logger_utils.dart';
import 'package:flutter_app/utils/sp_utils.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:flutter_app/values/CommonParam.dart';
import 'package:flutter_app/widget/upgrade/app_market.dart';
import 'package:flutter_app/widget/upgrade/app_upgrade.dart';
import 'package:flutter_app/widget/upgrade/download_status.dart';
import 'package:get/get.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import 'package:umeng_push_sdk/umeng_push.dart';

import '../GuidePage.dart';
import '../WebViewPage.dart';
import 'welcome_state.dart';

class WelcomeLogic extends GetxController {
  final WelcomeState state = WelcomeState();

  late AppUpgradeInfo appUpgradeInfo;

  @override
  void onInit() async {
    super.onInit();

    if (!await sp.contains(CommonParam.FIRST_OPEN)) {
      goToGuidePage();
    } else {
      // 判断是否要弹出 隐私政策
      if (await sp.getBool(CommonParam.FIRST_LOGIN) ?? true) {
        showFirstDialog();
      } else {
        initApp();
      }
    }
  }

  @override
  void onReady() async {
    super.onReady();
    /// 获取升级信息
    if (Platform.isAndroid) {
      if (await beyondDate()) {
        updateApp().then((updateAppEntity) async {
          if (updateAppEntity != null) {
            String build = await PackageInfoUtils().getBuildNumber();
            if (int.parse(updateAppEntity.build!) > int.parse(build)) {
              String title = updateAppEntity.versionShort!;
              List<String> contents = updateAppEntity.changelog!.split("；");
              setAppUpgradeInfo("新版本v$title", contents, false, updateAppEntity.installUrl!);
              showUpgradeDialog();
            }
          }
        });
      }
    }

    /// 获取配置信息
    postAppSetInfo().then((value) {
      AppSetInfoManager().setAppSetInfoEntity(value);
    });
  }

  /// 跳转页面
  goToPage() async {
    if (Platform.isIOS) {
      await Future.delayed(Duration(milliseconds: 500));
    }
    if (UserInfoManager().isLogin()) {
      // 跳转首页
      goToHomePage();
    } else {
      // 跳转登录页面
      goToLoginPage();
    }
  }

  /// 跳转首页
  goToHomePage() {
    Get.offAll(() => MainPage(title: '首页',));
  }

  /// 跳转登录页面
  goToLoginPage() {
    Get.offAll(() => LoginPage(title: "登陆"));
  }

  /// 跳转引导页面
  goToGuidePage(){
    Get.offAll(() => GuidePage(title: "引导页面",));
  }

  /// 弹窗 隐私政策
  showFirstDialog() {
    Future.delayed(Duration.zero, () {
      dialogUtils.showFirstDialog(
        context: Get.context!,
        callbackOk: () {
          sp.setBool(CommonParam.FIRST_LOGIN, false);
          Get.back();
          initApp();
        },
        callbackCancel: () {
          // SystemNavigator.pop();
          exit(0);
        },
        onTap: () {
          Get.to(() => WebViewPage(title: '用户协议和隐私政策', url: AppSetInfoManager().getAgreementUrl(),));
        },
      );
    });
  }

  // 初始化 app
  void initApp() async {
    // 初始化用户信心管理
    await UserInfoManager().init();
    // 初始化友盟sdk
    initUmeng();
    // 初始化高德地图sdk
    AMapUtils.setApiKey();
    AMapUtils.init();
    // 跳转页面
    goToPage();
  }

  /// 初始化友盟sdk
  void initUmeng(){
    //初始化组件化基础库, 所有友盟业务SDK都必须调用此初始化接口。
    UmengCommonSdk.initCommon(CommonParam.UMENG_ANDROID_APPKEY, CommonParam.UMENG_IOS_APPKEY, 'Umeng');
    // 收集方式为手动
    // UmengCommonSdk.setPageCollectionModeManual();
    // 收集方式为自动
    UmengCommonSdk.setPageCollectionModeAuto();


    UmengPushSdk.setTokenCallback((deviceToken) {
      print("Umeng deviceToken:" + deviceToken);
    });

    UmengPushSdk.setMessageCallback((msg) {
      print("Umeng receive custom:" + msg);
    });

    UmengPushSdk.setNotificationCallback((receive) {
      print("Umeng receive:" + receive);
    }, (open) {
      print("Umeng open:" + open);
    });

    // 日志
    UmengPushSdk.setLogEnable(false);
    // 初始化推送
    UmengPushSdk.register(CommonParam.UMENG_IOS_APPKEY, 'AppStore');
  }

  /// 获取配置信息
  Future<AppSetInfoEntity?> postAppSetInfo() async {
    Map<String, dynamic> param = {};
    ResultData resultData = await Api.postAppSetInfo(param);
    if (resultData.isSuccess) {
      AppSetInfoEntity appSetInfoEntity = AppSetInfoEntity.fromJson(resultData.data["data"]);
      return appSetInfoEntity;
    } else {
      // toast.show(resultData.data["message"]);
    }
  }

  /// 是否有新版本 需要升级  true是  false否
  Future<UpdateAppEntity?> updateApp() async {
    Map<String, dynamic> param = {
      "api_token": UrlPath.firImAppToken
    };
    ResultData resultData = await Api.updateApp(UrlPath.baseFirImUrl, param);
    if (resultData.isSuccess) {
      UpdateAppEntity? updateAppEntity = UpdateAppEntity.fromJson(resultData.data);
      return updateAppEntity;
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  /// 弹出 升级组件
  showUpgradeDialog() async {
    Future.delayed(Duration.zero, () {
      AppUpgrade.appUpgrade(
          Get.context!,
          getAppUpgradeInfo(),
          cancelText: '以后再说',
          okText: '马上升级',
          iosAppId: '1625617620',
          appMarketInfo: AppMarket.xiaoMi,
          onCancel: () {

          },
          onOk: () {

          },
          downloadProgress: (count, total) {

          },
          downloadStatusChange: (DownloadStatus status, {dynamic error}) {

          }
      );
    });
  }

  /// 设置 升级信息
  /// @param title    标题
  /// @param contents 升级内容 list String
  /// @param force    是否强制升级
  /// @param url      升级地址
  AppUpgradeInfo setAppUpgradeInfo(String title, List<String> contents, bool force, String url) {
    appUpgradeInfo = AppUpgradeInfo(
        title: title,
        contents: contents,
        force: force,
        apkDownloadUrl: url);
    return appUpgradeInfo;
  }

  /// 获取 升级信息
  getAppUpgradeInfo() {
    return Future.delayed(const Duration(seconds: 1), () {
      return this.appUpgradeInfo;
    });
  }

  /// 判断是否超过 7天 就显示  第一次也显示 ，只有在 7天之内不显示
  Future<bool> beyondDate() async {
    if (await sp.contains(CommonParam.UPGRADE_DATE)) {
      String? formattedString = await sp.getString(CommonParam.UPGRADE_DATE);
      DateTime upgradeDate = DateTime.parse(formattedString!);
      DateTime nowDate = DateTime.now();
      int day = nowDate.difference(upgradeDate).inDays;
      if (day >= 7) {
        await sp.remove(CommonParam.UPGRADE_DATE);
        DateTime dateTime = DateTime.now();
        sp.setString(CommonParam.UPGRADE_DATE, dateTime.toString());
      } else {
        return false;
      }
    } else {
      DateTime dateTime = DateTime.now();
      // 测试用 -7天
      // dateTime = dateTime.add(Duration(days: -7));
      sp.setString(CommonParam.UPGRADE_DATE, dateTime.toString());
    }
    return true;
  }

  @override
  void onClose() {
    super.onClose();
    UmengPushSdk.setTokenCallback(null);
    UmengPushSdk.setMessageCallback(null);
  }
}
